// CSS files are now imported globally in index.js
import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

import { Form, Input, Button, Checkbox, Typography, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

const { Title } = Typography;

function Login() {
  const formRef = useRef(null);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleClear = () => {
    if (formRef.current) {
      formRef.current.resetFields();
    }
  };

  const onFinish = async (values) => {
    console.log('Login attempt with:', values);
    setLoading(true);

    try {
      // 调用登录API
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        // 登录成功，存储token并跳转
        localStorage.setItem('token', data.token);
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
        message.success('Login successful!');
        navigate('/');
      } else {
        // 登录失败
        message.error(data.message || 'Login failed! Please check your username and password.');
      }
    } catch (error) {
      console.error('Login error:', error);
      message.error('Network error. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
    message.error('Form validation failed! Please check your input.');
  };

  return (
    <div className="App" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}>
      <Card
        title={<Title level={2} style={{ textAlign: 'center' }}>Login</Title>}
        variant="outlined"
        style={{
          width: '100%',
          maxWidth: '400px',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
          padding: '24px',
          border: 'none'
        }}
      >
        <Form name="login_form" ref={formRef} layout="vertical" initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} >
          <Form.Item name="username" label="Username" rules={[{ required: true, message: 'Please input your username!' }]}>
            <Input prefix={<UserOutlined />} placeholder="Enter your username" />
          </Form.Item>
          <Form.Item name="password" label="Password" rules={[{ required: true, message: 'Please input your password!' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="Enter your password" />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox>Remember me</Checkbox>
          </Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            Login
          </Button>
          <Button type="default" onClick={handleClear} >
            Clear
          </Button>
        </Form>
      </Card>
    </div>
  );
}

export default Login;